<!--
 * @Author: Bennty
 * @Date: 2024-12-12 10:26:08
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-12-16 10:25:14
 * @Description: 请填写简介
-->
<template>
    <el-dialog :model-value="props.visible" title="发货" width="35%" @close="handleClose">
        <el-form ref="formRef" :model="formData" label-width="auto">
            <el-form-item label="发货方式" prop="deliveryMethod" align="right">
                <el-select v-model="formData.deliveryMethod" placeholder="请选择">
                    <el-option v-for="item in send_type" :key="item.value" :label="item.label" :value="item.value" ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发货单号" prop="deliveryOrderCode" align="right">
                <el-input v-model="formData.deliveryOrderCode" placeholder="请输入" style="width:39%"></el-input>
            </el-form-item>
            <el-form-item label="聚水潭发货凭证" prop="fileUrl" align="right">
                <el-upload
                    class="upload"
                    ref="uploadRef"
                    drag
                    :action="uploadImgUrl"
                    :headers="headers"
                    :limit="1"
                    :on-success="handleSuccess" 
                    :before-upload="beforeUpload"
                    :on-exceed="handleExceed"
                    :auto-upload="true"
                >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        拖动文件 到这里 或 <em>点击上传</em>
                        <br />
                        csv/png/jpg
                    </div>
                </el-upload>
            </el-form-item>
            <el-form-item label="备注">
                {{ props.orderDetails.remark }}
            </el-form-item>
            <el-table :data="props.orderDetails.dataList" :summary-method="getTotalAmount" show-summary>
                <el-table-column label="品名" prop="specsDetail" align="center" width="400px"></el-table-column>
                <el-table-column label="数量" prop="number" align="center"></el-table-column>
                <el-table-column label="单价" prop="number" align="center"></el-table-column>
                <el-table-column label="总价" prop="needNumber" align="center"></el-table-column>
            </el-table>
            <span class="deliver-tip">订单编号一致时，合并到一起发货</span>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button  type="primary" @click="handleSubmit" >确 定</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { type FormInstance, UploadInstance, UploadProps,UploadRawFile } from 'element-plus';
import { globalHeaders } from "@/utils/request";
import { genFileId } from 'element-plus';
import type { VNode } from 'vue';
import { h } from 'vue'
import { orderDeliverApi } from '@/api/sj/productManagement/customizedOrder';

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const props = defineProps<{
    visible: boolean,
    send_type: any[],
    orderDetails: any
}>();
const emits = defineEmits(['close', 'submit']);
const formRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();
const formData = ref({
    deliveryMethod: undefined,
    deliveryOrderCode: undefined,
    fileUrl: undefined
});

const fileTypes = import.meta.env.VITE_APP_FILE_TYPE.split(',');

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!fileTypes.includes(rawFile.type)) {
        ElMessage.error('图片格式与要求不符')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片不可超过 5MB!')
        return false
    }
    return true
};

const handleSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // console.log(URL.createObjectURL(uploadFile.raw!),response);
    //@ts-ignore
    // formData.value.imageUrl = URL.createObjectURL(uploadFile.raw!);
    formData.value.fileUrl = response.data.url;
};

const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
};

/** 生成总计行 */
const getTotalAmount = (param: any) => {
    const {columns, data} = param;
    const sums: (string | VNode)[] = [];
    // console.log(columns, data);
    columns.forEach((column: any, index: number)=>{
        if(index == 0){
            sums[index] = h('div', { style: { textDecoration: 'underline' } }, ['合计']);
            return;
        };
        if(column.label == '总价'){
            const values = data.map((item: any)=>Number(item[column.property]));
            // console.log('values in', values);
            if(!values.every((value: any) => Number.isNaN(value))){
                sums[index] = `${
                    values.reduce((prev:any, curr:any)=>{
                        const value = Number(curr)
                        if(!Number.isNaN(value)){
                            return prev + curr;
                        }else{
                            return prev;
                        };
                    },0)
                }`
            }else{
                sums[index] = 'N/A';
            };
        };
    });
    return sums
};

const handleSubmit = async () => {
    const submitData = {
        ...formData.value,
        id: props.orderDetails.id,
        ids: [props.orderDetails.id]
    };
    const { code } = await orderDeliverApi(submitData);
};

const handleClose = () => {
    formRef.value?.resetFields();
    uploadRef.value?.clearFiles();
    emits('close');
};
</script>

<style lang="scss" scoped>
.upload{
    width: 40%;
    ::v-deep(.el-upload-dragger){
        height: 130px;
        padding: 20px 10px;
        .el-icon{
            font-size: 30px;
            margin-bottom: 5px;
            line-height: 30px;
        }
        .el-upload__text{
            font-size: 15px;
        }
    }
}
.deliver-tip{
    display: block;
    margin-top: 10px;
    font-size: 18px;
    color: red;
}
</style>